package com.llb666.shop.user.domain.service;

import com.llb666.common.core.constant.AppConstants;
import com.llb666.common.core.exception.AppException;
import com.llb666.common.core.utils.sign.MD5Utils;
import com.llb666.common.core.web.error.CommonError;
import com.llb666.shop.user.domain.entity.Users;
import com.llb666.shop.user.domain.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户接口 service.
 *
 * @author llb666
 */
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class UserService {

    private final UserRepository userRepository;

    /**
     * 判断用户名称是否存在.
     *
     * @param username 用户名
     * @return Boolean
     */
    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
    public Boolean queryUsernameIsExist(String username) {
        return userRepository.queryUsernameIsExist(username);
    }

    /**
     * 登录.
     *
     * @param user     用户
     * @return 用户信息
     * @throws Exception -
     */
    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
    public Users login(Users user) throws Exception {
        //2.查询
        Users result = userRepository.login(user.getUsername(), MD5Utils.getMD5Str(user.getPassword()));
        if (result == null) {
            throw new AppException(CommonError.NeedAuthentication, "用户名或密码错误密码！");
        }
        return result;
    }


    /**
     * 注册.
     *
     * @param user  用户实体
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Users register (Users user) {
        // 查找注册名是否重复.
        boolean isExist = userRepository.queryUsernameIsExist(user.getUsername());
        if (isExist) {
            throw new AppException(CommonError.RegisterInvalid, "用户名已经存在！");
        }
        // 实现注册.
        try {
            user.setFace(AppConstants.USER_FACE);
            userRepository.insertSelective(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        user.setPassword("");
        return user;
    }
}
